Skip to content

在 .NET Framework 裡,有關 Web.config (App.config) 的應用

TLDR

  • 使用組建組態(Build Configuration)搭配 Web.config Transform,可自動化產出對應環境的設定檔,避免手動修改錯誤。
  • 非 Web 專案(如 Console App)需安裝 SlowCheetah 套件才能啟用 Config Transform 功能。
  • 跨專案共用設定檔時,可透過 configSourcefile 屬性引用外部設定檔,並利用 TransformOnBuild 確保建置時自動轉換。
  • 若 IIS 子網站發生設定繼承衝突,可於父網站的 Web.config 使用 <location inheritInChildApplications="false"> 切斷繼承。
  • 使用 Entity Framework Database First 時,應避免將連線字串移至外部引用檔或使用 <location> 標籤包覆,以免導致設計階段 UI 無法讀取設定。

依不同組建組態發佈不同的設定檔

在開發、測試與正式環境中,設定檔內容通常不同。透過 Visual Studio 的組建組態(Build Configuration)與 Web.config Transform 機制,可以在發佈時自動產出對應環境的設定檔。

Web 專案的自動轉換

當專案中存在 Web.Debug.configWeb.Release.config 時,Visual Studio 會在發佈時根據選定的組態,將轉換規則套用到 Web.config

  • 什麼情況下會遇到這個問題:當專案缺少對應的轉換檔(如誤刪或新增組態)時。
  • 解決方式:在 Web.config 上點擊右鍵,選擇「新增設定轉換」(Add Config Transform)。
  • 轉換機制:使用 xdt:Transform 定義替換方式,並透過 xdt:Locator 定位節點。

常見轉換範例:

xml
<!-- 替換單一屬性 -->
<add key="MyKey" value="MyReleaseValue" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />

<!-- 移除特定屬性 -->
<compilation xdt:Transform="RemoveAttributes(debug)" />

<!-- 替換整個節點 -->
<connectionStrings xdt:Transform="Replace">
  <add name="Default" connectionString="{connectionString}" />
</connectionStrings>

非 Web 專案的轉換

非 Web 專案(如 .NET Framework Console App)預設不支援 Config Transform。

  • 什麼情況下會遇到這個問題:在非 Web 專案中希望自動轉換 App.config
  • 解決方式:安裝 NuGet 套件 Microsoft.VisualStudio.SlowCheetah。安裝後,App.config 右鍵選單會出現「Add Transform」選項,建置時即可觸發轉換。

不同專案共用設定檔

當方案(Solution)內有多個專案需共用同一組資料庫連線或 SMTP 設定時,可將設定抽離至獨立檔案。

設定步驟

  1. 建立外部設定檔:建立如 Connection.config 等檔案,並設定其 TransformOnBuildtrue
  2. 專案檔 (csproj) 設定
    • 將外部設定檔加入專案,並設定 <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    • 將轉換檔(如 Connection.Release.config)設為 <None /> 並透過 <DependentUpon> 連結至主設定檔。
  3. 引用方式
    • Web.configApp.config 中使用 configSourcefile 屬性引用。

引用範例:

xml
<!-- Web.config -->
<connectionStrings configSource="bin\Connection.config" />
<appSettings file="bin\AppGlobal.config">
  <add key="MyKey" value="MyValue" />
</appSettings>

WARNING

若使用 Entity Framework 的 Database First 模式,請勿將連線字串移至外部引用檔,否則 Entity Framework 的設計階段 UI 將無法讀取到連線字串。


切斷 Web.config 的繼承關係

IIS 允許在網站下建立子應用程式,但子應用程式會繼承父層的 Web.config 設定,可能導致 Framework 版本衝突。

  • 什麼情況下會遇到這個問題:子網站與父網站的設定發生衝突,或兩者 Framework 版本不一致時。
  • 解決方式:在父網站的 Web.config 中使用 <location> 標籤。
xml
<location path="." inheritInChildApplications="false">
  <system.web>
    <!-- 相關設定 -->
  </system.web>
</location>

TIP

切勿將 <location> 標籤包覆在 <connectionStrings> 外層,同樣會導致 Entity Framework 的 UI 無法讀取連線字串。


異動歷程

    • 初版文件建立。